package com.wenbo.service;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.wenbo.dao.IRelationshipDao;
import com.wenbo.dao.IUserInfoDao;
import com.wenbo.model.Relationship;
import com.wenbo.model.UserInfo;

@Component(value="relationshipSerivce")
public class RelationshipSerivceImpl implements IRelationshipService {
	
	@Resource
	private IRelationshipDao relationshipDao;
	
	@Resource
	private IUserInfoDao userInfoDao;

	@Override
	public boolean addFriendShip(String username1, String username2)throws Exception {
		boolean flag = false;
		Relationship relationship = new Relationship();
		UserInfo userinfo1 = this.userInfoDao.findUserInfoByName(username1);
		UserInfo userinfo2 = this.userInfoDao.findUserInfoByName(username2);
		relationship.setUserId(userinfo1.getId());
		relationship.setFriendId(userinfo2.getId());
		this.relationshipDao.save(relationship);
		relationship = new Relationship();
		relationship.setUserId(userinfo2.getId());
		relationship.setFriendId(userinfo1.getId());
		this.relationshipDao.save(relationship);
		flag = true;
		return flag;
	}

	@Override
	public boolean destroyFriendship(String username1, String username2)
			throws Exception {
		boolean flag = false;
		Relationship relationship = new Relationship();
		UserInfo userinfo1 = this.userInfoDao.findUserInfoByName(username1);
		UserInfo userinfo2 = this.userInfoDao.findUserInfoByName(username2);
		relationship.setUserId(userinfo1.getId());
		relationship.setFriendId(userinfo2.getId());
		relationship = this.relationshipDao.find(findByDetachedCriteria(relationship)).get(0);
		this.relationshipDao.remove(relationship.getId());
		relationship = new Relationship();
		relationship.setUserId(userinfo2.getId());
		relationship.setFriendId(userinfo1.getId());
		relationship = this.relationshipDao.find(findByDetachedCriteria(relationship)).get(0);
		this.relationshipDao.remove(relationship.getId());
		flag = true;
		return flag;
	}
	
	private DetachedCriteria findByDetachedCriteria(Relationship relationship)
	{
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Relationship.class);
		if(relationship.getUserId() != null)
		{
			detachedCriteria.add(Restrictions.eq("userId",relationship.getUserId()));
		}
		if(relationship.getFriendId() != null)
		{
			detachedCriteria.add(Restrictions.eq("friendId",relationship.getFriendId()));
		}
		return detachedCriteria;
	}
	
	

}
